package org.fxkj.cloud.uaa.service.security;

import lombok.RequiredArgsConstructor;
import org.fxkj.cloud.uaa.service.security.model.token.JwtTokenFactory;
import org.fxkj.cloud.uaa.service.security.model.token.RawAccessJwtToken;
import org.fxkj.cloud.uaa.service.security.model.token.RefreshAuthenticationToken;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

/**
 * <p>Description: </p>
 *
 * @author Wei, Wu
 * @create 2024/11/19 8:41
 */
@Component
@RequiredArgsConstructor
public class WRefreshAuthenticationProvider implements AuthenticationProvider {
    private final JwtTokenFactory tokenFactory;
    private final UserService userService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        Assert.notNull(authentication, "No authentication data provided");
        RawAccessJwtToken rawAccessToken = (RawAccessJwtToken) authentication.getCredentials();
        SecurityUser unsafeUser = tokenFactory.parseRefreshToken(rawAccessToken.getToken());

        return new RefreshAuthenticationToken(authenticateByUserName(unsafeUser.getUsername()));
    }

    private SecurityUser authenticateByUserName(String userName) {
        SecurityUser user = userService.loadUserByUsername(userName);
        return user;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return  RefreshAuthenticationToken.class.isAssignableFrom(authentication);
    }
}
